package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Zonghe Wang
 * @Date: 2025/1/26 15:23
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 用于存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dates = StringUtils.join(dateList, ",");//lang3的StringUtils拼接字符串


        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 查询date日期的营业额,订单已完成的sum(amount)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // select sum(amount) from orders where order_time between ? and ? and status = 5
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        String turnover = StringUtils.join(turnoverList, ",");//lang3的StringUtils拼接字符串

        return TurnoverReportVO.builder()
                .dateList(dates)
                .turnoverList(turnover)
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 用于后续查询 需要begin
        Map map = new HashMap();
        map.put("end", LocalDateTime.of(begin, LocalTime.MIN));

        // 构造dateList
        while(!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天新增用户数量 select count(*) from user where create_time < ? and create_time > ?
        List<Integer> newUserList = new ArrayList<>();
        // 存放截至某天总用户数量
        List<Integer> totalUserList = new ArrayList<>();


        Integer beginTotal = userMapper.countByMap(map);

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 新增用户数量
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

            beginTotal += newUser;
            totalUserList.add(beginTotal);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        // 存每天有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        // 查询每一天的有效订单数、订单总数
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //  查总数 select count(*) from orders where order_time > ? and order_time < ?
            Integer total = getOrderCount(beginTime, endTime, null);
            // 查有效订单数 select count(*) from orders where order_time > ? and order_time < ? and status = 5
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(total);
            validOrderCountList.add(validOrderCount);
        }

        Integer sum = orderCountList.stream().reduce(Integer::sum).get();
        Integer validSum = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate =  0.0;
        if(sum != 0) orderCompletionRate = validSum.doubleValue()/sum;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(sum)
                .validOrderCount(validSum)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // select od.name,sum(od.number) number from order_detail od, order o where od.order_id = o.id and o.status = 5 o.order_time > ? and o.order_time < ? group by od.name order by number desc limit 0,10
        List<GoodsSalesDTO> top10 =  orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /*
    导出运营数据报表
     */
    public void exportBusinessData(HttpServletResponse response) {
        // 1. 查询数据库 获取运营数据 --- 查询最近30天的运营数据
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = LocalDate.now().plusDays(-29);
        // 查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        try {
            // 2. 通过POI将数据接入excel
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            // 基于模板文件创建新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间： "+begin+" 至 "+end);
            // 填充数据--营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            // 填充数据--订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            // 填充数据--新增用户数目
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            // 填充数据--有效订单数
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            // 填充数据--平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            // 明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                // 填充数据--日期
                row.getCell(1).setCellValue(date.toString());
                // 填充数据--营业额
                row.getCell(2).setCellValue(data.getTurnover());
                // 填充数据--有效订单数
                row.getCell(3).setCellValue(data.getValidOrderCount());
                // 填充数据--订单完成率
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                // 填充数据--平均客单价
                row.getCell(5).setCellValue(data.getUnitPrice());
                // 填充数据--新增用户数目
                row.getCell(6).setCellValue(data.getNewUsers());
            }

            // 3. 通过输出流，将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            excel.close();
            out.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }
}
